/*
 * JsonObject.cpp
 *
 *  Created on: Jun 2, 2011
 *      Author: ToanNhan
 */

#include "../../../inc/Utility/Json/JsonObject.h"
#include "../../../inc/Utility/Json/JsonString.h"

//Member
JsonObject::Member::Member(){
	this->value = null;
	this->key = L"";
}

JsonObject::Member::Member(String key, JsonValue *value){
	if (value == null){
		this->value = (JsonValue*)(new JsonString()) ;
	}
	else{
		this->value = value->cloneN();
	}
	this->key = key;
}

JsonObject::Member::~Member(){
	if (this->value != null){
		delete this->value;
	}
}

JsonObject::Member::Member(const Member& member){
	this->value = member.value->cloneN();
	this->key = member.key;
}

const JsonObject::Member& JsonObject::Member::operator =(const JsonObject::Member &member){
	if (this == &member){
		return member;
	}
	if (this->value != null){
		delete this->value;
	}
	this->value = member.value->cloneN();
	this->key = member.key;
	return member;
}

JsonValue* JsonObject::Member::getValueN(){
	if (this->value != null){
		return this->value->cloneN();
	}
	return null;
}

String JsonObject::Member::getKey(){
	return this->key;
}

void JsonObject::Member::setKey(String key){
	this->key = key;
}

void JsonObject::Member::setValue(JsonValue *value){
	if (value != null){
		this->value = value->cloneN();
	}else{
		this->value = null;
	}
}

String JsonObject::Member::toJsonString(){
	String temp = "\"";
	temp += key + "\":";
	temp += value->toJsonString();
	return temp;
}

//JsonObject

int JsonObject::getSize(){
	return (int)members.size();
}

JsonValue* JsonObject::getValueN(String key){
	JsonValue* value = null;
	vector<Member>::iterator it;

	for (it = members.begin(); it != members.end(); it++){
		if (it->getKey().CompareTo(key) == 0){
			value = it->getValueN();
			break;
		}
	}

	return value;
}
JsonValue* JsonObject::getValueN(int index){
	JsonValue* value = null;

	if (index >= 0 && index < (int)members.size()){
		value = members[index].getValueN();
	}else{
		throw "JsonObject::getValueN: Error: out of range";
	}

	return value;
}

void JsonObject::insertValue(String key, JsonValue* value){
	Member member(key, value);
	members.push_back(member);
}

void JsonObject::insertValue(JsonObject::Member member){
	members.push_back(member);
}

String JsonObject::toJsonString(){
	String temp = L"{";
	if (members.size() > 0){
		int length = (int)members.size() - 1;
		for (int i = 0; i < length; i++){
			temp += members[i].toJsonString();
			temp += L",";
		}
		temp += members[length].toJsonString();
	}
	temp += L"}";
	return temp;
}

JsonObject* JsonObject::cloneN(){
	return new JsonObject(*this);
}

JsonObject::~JsonObject(){

}

JsonObject::JsonObject(){
	jsonValueType = JSON_OBJECT;
}





